var sqlite3 = require('sqlite3').verbose();
var fs = require('fs');
var CreatDBSql = [
    // 选项表
    `CREATE TABLE option (
key         CHAR(50)    PRIMARY KEY     NOT NULL,
value       CHAR(50)                    NOT NULL
);`,
    // 用户表
    `CREATE TABLE user (
user_id     CHAR(36)    PRIMARY KEY     NOT NULL,
username    CHAR(16)                    NOT NULL,
password    CHAR(16)                    NOT NULL,
avater      CHAR(500)                   NOT NULL,
nickname    CHAR(8)                     NOT NULL,
disable     INT(2)                      NOT NULL,
update_time INT(14),
create_time INT(14)
);`,
    // 链接服务表
    `CREATE TABLE service (
service_id      CHAR(36)    PRIMARY KEY     NOT NULL,
title           CHAR(16)                    NOT NULL,
ip              CHAR(500)                   NOT NULL,
username        CHAR(16)                    NOT NULL,
password        CHAR(16)                    NOT NULL,
update_time     INT(14),
create_time     INT(14)
);`,
    // 项目表
    `CREATE TABLE project (
project_id  CHAR(36)    PRIMARY KEY     NOT NULL,
owner_user  CHAR(36)                    NOT NULL,
title       CHAR(16)                    NOT NULL,
description CHAR(500),
update_time INT(14),
create_time INT(14)
);`,
    // 文件夹表
    `CREATE TABLE folder (
folder_id             CHAR(36)      PRIMARY KEY     NOT NULL,
folder_project_id     CHAR(36)                      NOT NULL,
folder_parent_id      CHAR(36),
title                 CHAR(255)                     NOT NULL,
type                  CHAR(255)                     NOT NULL,
description           CHAR(1000),
folder_index_array    CHAR(10000),
child_index_array     CHAR(10000),
disable               INT(2)                        NOT NULL,
update_time           INT(14),
create_time           INT(14)
);`,
    // 项目成员表
    `CREATE TABLE project_user (
project_user_id     CHAR(36)      PRIMARY KEY   NOT NULL,
project_id          CHAR(36)                    NOT NULL,
user_id             CHAR(36)                    NOT NULL,
update_time         INT(14),
create_time         INT(14)
);`,
    // 项目URL表
    `CREATE TABLE project_url (
url_id              CHAR(36)      PRIMARY KEY   NOT NULL,
project_id          CHAR(36)                    NOT NULL,
str                 CHAR(500)                   NOT NULL,
title               CHAR(255)                   NOT NULL,
disable             INT(2)                      NOT NULL,
update_time         INT(14),
create_time         INT(14)
);`,
    // 项目model表
    `CREATE TABLE project_model (
model_id            CHAR(36)      PRIMARY KEY   NOT NULL,
project_id          CHAR(36)                    NOT NULL,
key                 CHAR(500)                   NOT NULL,
name                CHAR(255)                   NOT NULL,
text                CHAR(10000)                 NOT NULL,
update_time         INT(14),
create_time         INT(14)
);`,
    // 项目Api表
    `CREATE TABLE project_api (
api_id          CHAR(36)      PRIMARY KEY     NOT NULL,
project_id      CHAR(36)                      NOT NULL,
folder_id       CHAR(36)                      NOT NULL,
title           CHAR(225)                     NOT NULL,
type            CHAR(10)                      NOT NULL,
body_type       INT(2),
disable         INT(2),
status          INT(2),
description     CHAR(200),   
url             CHAR(255),
header          CHAR(3000),
body            CHAR(3000),
fromdata        CHAR(3000),
query           CHAR(3000),
rest            CHAR(3000),
before          CHAR(3000),
after           CHAR(3000),
update_time     INT(14),
create_time     INT(14)
);`,
    // 项目功能表
    `CREATE TABLE project_function (
function_id      CHAR(36)      PRIMARY KEY     NOT NULL,
project_id       CHAR(36)                      NOT NULL,
name             CHAR(225)                     NOT NULL,
key              CHAR(225)                     NOT NULL,
str              CHAR(10000)                   NOT NULL,
testStr          CHAR(255),
update_time      INT(14),
create_time      INT(14)
);`,
    // 项目缓存表
    `CREATE TABLE project_cache (
cache_id        CHAR(36)      PRIMARY KEY     NOT NULL,
project_id      CHAR(36)                      NOT NULL,
key             CHAR(225)                     NOT NULL,
name            CHAR(225)                     NOT NULL,
update_time     INT(14),
create_time     INT(14)
);`,
    // 项目存储本地缓存表
    `CREATE TABLE local_api_cache (
cache_id        CHAR(36)      PRIMARY KEY     NOT NULL,
project_id      CHAR(36)                      NOT NULL,
service_id      CHAR(36)                      NOT NULL,
key             CHAR(255)                     NOT NULL,
value           CHAR(255)                     NOT NULL,
update_time     INT(14),
create_time     INT(14)
);`,
    // 项目自定义Key值表
    `CREATE TABLE project_custom_key (
custom_key_id   CHAR(36)      PRIMARY KEY     NOT NULL,
project_id      CHAR(36)                      NOT NULL,
key             CHAR(255),
update_time     INT(14),
create_time     INT(14)
)`
];


var formatObject = function (res) {
    console.log(res);
    let _data = {};
    for (const key in res) {
        if (res.hasOwnProperty(key)) {
            const _item = res[key];
            var index = key.indexOf('_');
            if (index != -1) {
                var _indexArray = key.split('_');
                var _$indexArray = [];
                for (let i = 0; i < _indexArray.length; i++) {
                    const element = _indexArray[i];
                    if (i != 0) {
                        _$indexArray.push(element[0].toUpperCase() + element.substr(1));
                    } else {
                        _$indexArray.push(element);
                    };
                };
                var _key = _$indexArray.join('');
                _data[_key] = _item;
            } else {
                _data[key] = _item;
            };
        }
    };
    return _data;
};
var formatArray = function (res) {
    var data = [];
    for (let i = 0; i < res.length; i++) {
        const element = res[i];
        var _data = formatObject(element);
        data.push(_data);
    };
    return data;
};


class _DB_ {
    constructor() {
        this.filePath = './test.db';
        this.event = {
            ready: [],
        };
        this.init();
    }
    async init() {
        this.hasFile = fs.existsSync(this.filePath);
        if (!this.hasFile) {
            console.log('CreatDB File');
            fs.openSync(this.filePath, 'w');
            this.db = new sqlite3.Database(this.filePath, function (err) { });
            for (let i = 0; i < CreatDBSql.length; i++) {
                const element = CreatDBSql[i];
                await this.createTable(element);
            };
            this.setDefaultData();
        } else {
            this.db = new sqlite3.Database(this.filePath, function (err) { });
        };
    }
    async setDefaultData() {
        await this.creat(`INSERT INTO option values('version','3.0.0')`);
        await this.creat(`INSERT INTO option values('theme','theme-light')`);
    }
    createTable(sql) {
        return new Promise((resolve, rejected) => {
            this.db.run(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(res);
                };
            });
        });
    }
    creat(sql) {
        return new Promise((resolve, rejected) => {
            this.db.run(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(res);
                };
            });
        });
    }
    update(sql) {
        return new Promise((resolve, rejected) => {
            this.db.run(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(res);
                };
            });
        });
    }
    find(sql) {
        return new Promise((resolve, rejected) => {
            this.db.all(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(formatArray(res));
                };
            });
        });
    }
    get(sql) {
        return new Promise((resolve, rejected) => {
            this.db.get(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(formatObject(res));
                };
            });
        });
    }
    delete(sql) {
        return new Promise((resolve, rejected) => {
            this.db.run(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(res);
                };
            });
        });
    }
}

module.exports = _DB_;

